package com.shengruan.admin.action;

import com.shengruan.admin.jdbc.ShippingJdbc;
import com.shengruan.admin.vo.Shipping;
import com.shengruan.common.BaseAction;
import com.shengruan.common.Constants;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class ShippingAction extends BaseAction {

    Logger logger = LoggerFactory.getLogger(getClass());
    private ShippingJdbc shippingJdbc = (ShippingJdbc) this.getJdbc(ShippingJdbc.class);

    public void list() throws Exception {
        List<Shipping> shippingList = this.shippingJdbc.findAll();
        this.setRequest("shippingList", shippingList);
        this.forward("/admin/system/shipping-list.jsp");
    }


    /**
     * 添加商品
     *
     * @throws Exception
     */
    public void add() throws Exception {
        String name = this.input("name");
        String amount = this.input("amount");

        Shipping shipping = new Shipping();
        shipping.setName(StringUtils.trim(name));
        shipping.setAmount(Double.valueOf(StringUtils.trim(amount)));
        shipping.setCreationTime(System.currentTimeMillis());
        this.shippingJdbc.save(shipping);

        this.setRequest(Constants.MESSAGE, "添加送方式成功。");
        this.redirect("/admin/system/shipping-list.ac");
    }

    public void getById() throws Exception {
        String id = this.input("id");
        Shipping shipping = this.shippingJdbc.getById(Integer.valueOf(id));

        this.setRequest("shipping", shipping);
        this.forward("/admin/system/shipping-edit.jsp");
    }

    public void edit() throws Exception {
        String id = this.input("id");
        String name = this.input("name");
        String amount = this.input("amount");

        Shipping shipping = this.shippingJdbc.getById(Integer.valueOf(id));
        shipping.setName(StringUtils.trim(name));
        shipping.setAmount(Double.valueOf(StringUtils.trim(amount)));

        this.shippingJdbc.update(shipping);


        this.setRequest(Constants.MESSAGE, "修改送方式成功。");
        this.redirect("/admin/system/shipping-list.ac");
    }

    public void delete() throws Exception{
        try {
            String id = this.input("id");
            this.shippingJdbc.deleteById(Integer.valueOf(id));
        } catch (Exception e) {
            this.setRequest(Constants.MESSAGE, "您不能删除已经被使用的配送方式。");
            try {
                this.list();
                return;
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }

        this.setRequest(Constants.MESSAGE, "删除送方式成功。");
        this.redirect("/admin/system/shipping-list.ac");
    }
}
